package com.hunantv.mglive.ui.entertainer;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BaseActionActivity;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarModel;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.TagViewGroup;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class StarTagActivity extends BaseActionActivity implements TextWatcher, View.OnClickListener, View.OnFocusChangeListener {
    public static final String KEY_STAR = "KEY_STAR";
    private RelativeLayout starLayout;
    private ImageView starIconImg;
    private TextView starNameText, animationText;
    private TagViewGroup tagViewGroup;
    private TagViewGroup inputGroup;
    private Button submitBtn;
    private EditText inputTagText;
    private View inputClickCiew;
    private View tagClickCiew;

    private StarModel starModel;
    private boolean mCancelSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_star_tag);
        setTitle("艺人印象");
        initData();

        findView();
        loadStarInfo();
    }

    private void findView() {
        starLayout = (RelativeLayout) findViewById(R.id.starLayout);
        starLayout.setOnClickListener(this);
        starIconImg = (ImageView) findViewById(R.id.starIconImg);
        starNameText = (TextView) findViewById(R.id.starNameText);
        tagViewGroup = (TagViewGroup) findViewById(R.id.tagViewGroup);
        inputGroup = (TagViewGroup) findViewById(R.id.inputGroup);
        submitBtn = (Button) findViewById(R.id.submitBtn);
        submitBtn.setOnClickListener(this);
        tagClickCiew = (View) findViewById(R.id.tagClickCiew);
        tagClickCiew.setOnClickListener(this);
        inputClickCiew = (View) findViewById(R.id.inputClickCiew);
        inputClickCiew.setOnClickListener(this);
        animationText = (TextView) findViewById(R.id.animationText);
    }

    private void loadStarInfo() {
        //刷新列表
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", starModel.getUid())
                .build();
        post(BuildConfig.URL_STAR_INFO, body);
    }

    private void initView() {
        if (starModel != null) {
            Glide.with(this).load(StringUtil.isNullorEmpty(starModel.getPhoto()) ? R.drawable.default_icon : starModel.getPhoto())
                    .placeholder(R.drawable.default_icon_preload).error(R.drawable.default_icon)
                    .transform(new GlideRoundTransform(this, R.dimen.height_55dp)).into(starIconImg);
            starNameText.setText(starModel.getNickName());

            notifyTags(starModel.getTags());

            inputGroup.removeAllViews();
            LayoutInflater layoutInflater = LayoutInflater.from(this);
            View view = layoutInflater.inflate(
                    R.layout.layout_input_tag_btn, null);
            inputTagText = (EditText) view.findViewById(R.id.inputTagText);
            inputTagText.setText(" ");
            inputTagText.setSelection(inputTagText.getText().length());
            inputTagText.addTextChangedListener(this);
            inputTagText.setOnFocusChangeListener(this);
            inputGroup.addView(view);
        }

    }

    private void initData() {
        starModel = (StarModel) getIntent().getSerializableExtra(KEY_STAR);
    }

    private void addInputTag(String text) {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View view = layoutInflater.inflate(
                R.layout.layout_add_tag_btn, null);
        TextView tagBtn = (TextView) view.findViewById(R.id.tagBtn);
        tagBtn.setText(text);
        view.setTag(text);
        inputGroup.addView(view, inputGroup.getChildCount() - 1);

    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v.getId() == R.id.inputTagText) {
            if (!hasFocus) {
                //失去焦点
                String text = inputTagText.getText().toString();
                String trimText = text.toString().trim();
                if (!"".equals(trimText) && trimText.length() > 0) {
                    byte[] data = trimText.getBytes();
                    int bytelength = data.length;
                    int strlength = trimText.length();

                    if ((bytelength - strlength) % 2 != 0 || bytelength > 15 || strlength > 10) {
                        mCancelSubmit = true;
                        return;
                    } else {
                        int x = (bytelength - strlength) / 2;
                        int y = strlength - x;
                        if (x * 2 + y > 10) {
                            mCancelSubmit = true;
                            return;
                        }
                    }
                    addInputTag(trimText);
                    inputTagText.setText(" ");
                }
            } else {
                if (!mCancelSubmit) {
                    inputTagText.setText(" ");
                    inputTagText.setSelection(inputTagText.getText().length());
                }
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence text, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        changeEditText(s.toString());
    }

    @Override
    public void afterTextChanged(Editable s) {
        if (" ".equals(s.toString())) {
            inputTagText.setSelection(inputTagText.getText().length());
        }

    }

    private void changeEditText(String text) {
        String trimText = text.trim();
        mCancelSubmit = false;
        if (!"".equals(trimText) && text.endsWith(" ") && text.length() >= 2) {
            byte[] data = trimText.getBytes();
            int bytelength = data.length;
            int strlength = trimText.length();

            if ((bytelength - strlength) % 2 != 0 || bytelength > 15 || strlength > 10) {
                Toast.makeText(this, "不能超过5个字哦！", Toast.LENGTH_SHORT).show();
                mCancelSubmit = true;
                return;
            } else {
                int x = (bytelength - strlength) / 2;
                int y = strlength - x;
                if (x * 2 + y > 10) {
                    Toast.makeText(this, "不能超过5个字哦！", Toast.LENGTH_SHORT).show();
                    mCancelSubmit = true;
                    return;
                }
            }
            addInputTag(trimText);
            inputTagText.setText(" ");
        }
        if (text.length() <= 0) {
            if (inputGroup.getChildCount() > 1) {
                View view = inputGroup.getChildAt(inputGroup.getChildCount() - 2);
                inputGroup.removeView(view);
                inputTagText.setText(" ");
                inputTagText.setSelection(inputTagText.getText().length());
            }

        }
    }

    @Override
    public void onClick(View v) {
            if(v.getId() == R.id.tagClickCiew){
                changeInputFlag();
            }else if(v.getId() == R.id.inputClickCiew){
                changeInputFlag();
            }else if(v.getId() == R.id.submitBtn){
                if (!isLogin()) {
                    jumpToLogin("登录以后才可以添加标签哦~");
                    return;
                }
                if (mCancelSubmit) {
                    Toast.makeText(this, "不能超过5个字哦！", Toast.LENGTH_SHORT).show();
                    return;
                }
                String tags = getTags();
                L.d(TAG, tags);
                if (!"".equals(tags)) {
                    addTags(tags);
                    cleanInputTags();
                    String[] tagArray = tags.split(",");
                    addTagsToView(Arrays.asList(tagArray));
                }
            }

    }

    private void addTags(String tags) {
        L.d("ADDTAGS", tags + "==");
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", getUid())
                .add("tags", tags)
                .add("followid", starModel.getUid())
                .build();
        post(BuildConfig.URL_ADD_TAGS, body);
    }

    private void changeInputFlag() {

        if (inputTagText != null && !inputTagText.isFocused()) {
            showInputTag();
        } else {
            hideInputTage();
        }
    }

    private void showInputTag() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //输入框获得焦点
        inputTagText.requestFocus();
        inputTagText.requestFocusFromTouch();
        //打开软键盘
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        imm.showSoftInputFromInputMethod(inputTagText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        inputClickCiew.setVisibility(View.GONE);
        tagClickCiew.setVisibility(View.VISIBLE);
    }

    private void hideInputTage() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if(inputTagText != null && inputClickCiew != null && tagClickCiew != null){
            inputTagText.clearFocus();
            imm.hideSoftInputFromWindow(inputTagText.getWindowToken(), 0);
            inputClickCiew.setVisibility(View.VISIBLE);
            tagClickCiew.setVisibility(View.GONE);
        }
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException {
        if (BuildConfig.URL_ADD_TAGS.equals(url)) {

            //刷新列表
//            loadStarInfo();
        } else if (BuildConfig.URL_STAR_INFO.equals(url)) {
            starModel = JSON.parseObject(resultModel.getData(), StarModel.class);
            List<String> tagList = starModel.getTags();
            ArrayList<String> tags = new ArrayList<String>();
            for (String tagJson : tagList) {
                JSONObject jsonObject = new JSONObject(tagJson);
                if (!jsonObject.isNull("name")) {
                    String tagName = jsonObject.getString("name");
                    tags.add(tagName);
                }
            }
            starModel.setTags(tags);
//
//            notifyTags(tags);

            initView();
        }
        super.onSucceed(url, resultModel);
    }

    private String getTags() {
        hideInputTage();
        StringBuilder sb = new StringBuilder();
        int size = inputGroup.getChildCount();
        for (int i = 0; i < size - 1; i++) {
            View view = inputGroup.getChildAt(i);
            Object tagObj = view.getTag();
            String tag = tagObj.toString().trim();
            if (!StringUtil.isNullorEmpty(tag)) {
                sb.append(tag).append(",");
            }
        }
        String text = sb.toString();
        if (text.endsWith(",")) {
            return text.substring(0, text.length() - 1);
        }
        return text;
    }

    private void notifyTags(List<String> tags) {
        tagViewGroup.removeAllViews();
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        if (tags != null && tags.size() > 0) {
            for (int i = 0; i < tags.size(); i++) {
                View view = layoutInflater.inflate(
                        R.layout.layout_tag_btn, null);
                TextView tagBtn = (TextView) view.findViewById(R.id.tagBtn);

                tagBtn.setText(tags.get(i));
                view.setTag(tags.get(i));
                view.setOnClickListener(new StarTagClickListener(tagBtn));
                tagViewGroup.addView(view);
                //                inputGroup.addView(view);
            }
        } else {
            View view = layoutInflater.inflate(
                    R.layout.layout_tag_btn, null);
            view.setBackgroundResource(0);
            TextView tagBtn = (TextView) view.findViewById(R.id.tagBtn);
            tagBtn.setText("什么？！还没人给她添加印象？放着我来！");
            tagBtn.setPadding(0, 0, 0, 0);
            tagViewGroup.addView(view);
        }
    }

    private void addTagsToView(List<String> tags) {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        if (tags != null && tags.size() > 0) {
            for (int i = 0; i < tags.size(); i++) {
                String tag = tags.get(i);
                if (!StringUtil.isNullorEmpty(tag)) {
                    View view = layoutInflater.inflate(
                            R.layout.layout_tag_btn, null);
                    TextView tagBtn = (TextView) view.findViewById(R.id.tagBtn);

                    tagBtn.setText(tags.get(i));
                    view.setTag(tags.get(i));
                    view.setOnClickListener(new StarTagClickListener(tagBtn));
                    tagViewGroup.addView(view);
                    //                inputGroup.addView(view);
                }
            }
        }
    }

    private void cleanInputTags() {
        int size = inputGroup.getChildCount();
        if (size > 1) {
            for (int i = size - 2; i >= 0; i--) {
                View view = inputGroup.getChildAt(i);
                if (view != null && !(view instanceof EditText)) {
                    inputGroup.removeView(view);
                }

            }
        }
    }

    private class StarTagClickListener implements View.OnClickListener {
        private TextView view;

        public StarTagClickListener(TextView view) {
            this.view = view;
        }

        @Override
        public void onClick(View v) {
            if (!isLogin()) {
                jumpToLogin("登录以后才可以添加标签哦~");
                return;
            }
            Boolean bool = (Boolean) view.getTag();
            if (bool == null || !bool) {
                int bottom = view.getPaddingBottom();
                int top = view.getPaddingTop();
                int right = view.getPaddingRight();
                int left = view.getPaddingLeft();
                view.setBackgroundResource(R.drawable.star_flower_tag_bg);
                view.setPadding(left, top, right, bottom);
                view.setTextColor(getResources().getColor(R.color.white));
                Animation animation = getCenter2CenterAnimation(animationText, view, starIconImg);
                animation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                        animationText.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        animationText.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                animation.setDuration(800);
                animationText.startAnimation(animation);
                view.setTag(Boolean.TRUE);
                addTags(view.getText().toString());
            }
        }
    }

    private Animation getCenter2CenterAnimation(View animView, View starView, View endView) {
        int[] textPosition = new int[2];
        animView.getLocationOnScreen(textPosition);
        textPosition[0] = textPosition[0] + animView.getWidth() / 2;
        textPosition[1] = textPosition[1] + animView.getHeight() / 2;

        int[] animPosition = new int[2];
        starView.getLocationOnScreen(animPosition);
        animPosition[0] = animPosition[0] + starView.getWidth() / 2;
        animPosition[1] = animPosition[1] + starView.getHeight() / 2;

        int[] iconPosition = new int[2];
        endView.getLocationOnScreen(iconPosition);
        iconPosition[0] = iconPosition[0] + endView.getWidth() / 2;
        iconPosition[1] = iconPosition[1] + endView.getHeight() / 2;

        int starX = animPosition[0] - textPosition[0];
        int endX = iconPosition[0] - textPosition[0];
        int starY = animPosition[1] - textPosition[1];
        int endY = iconPosition[1] - textPosition[1];

        Animation animation = new TranslateAnimation(
                Animation.ABSOLUTE, starX,
                Animation.ABSOLUTE, endX,
                Animation.ABSOLUTE, starY,
                Animation.ABSOLUTE, endY);
        return animation;
    }
}
